'''
#Coding: utf-8
#Project: online-exam
#Author: rtf
#Time: 2022-08-01 18:39:10
#FileName: student_answer.py
#Softwar: PyCharm
'''


import json
import random
from trump.query import get_item, get_items, create_item, modify_item
from trump.utils import ok, fail
from trump.decorators import table_headers
from utils.params_validate_decorator import validate_params
from funcs.user_info import get_uesr_info
from trump.utils import get_user


async def post(app, request):
    params = request.json
    student_answer = params.get("student_answer")
    for x in student_answer:
        if isinstance(student_answer.get(x), list):
            student_answer[x] = "".join(s for s in student_answer.get(x))
    params["student_answer"] = json.dumps(student_answer)


async def post_post(app, request, data):
    params = request.json
    exam_paper_id = params.get("exam_paper_id")
    student_exam_id = params.get("student_exam_id")
    exam_paper = await get_item(app.ctx.pool, "exam_paper", exam_paper_id)
    exam_questions = json.loads(exam_paper.get("exam_questions"))
    student_answer = json.loads(params.get("student_answer"))
    questions_answer = dict()
    questions_score = dict()
    for x in exam_questions:
        questions = x.get("questions")
        for s in questions:
            if s.get("subject_type") != "questions":
                questions_answer[str(s.get("no"))] = s.get("answer")
                questions_score[str(s.get("no"))] = s.get("score")
    score = 0
    for x in questions_answer:
        if questions_answer.get(str(x)) == student_answer.get(str(x)):
            score += questions_score.get(str(x))

    await modify_item(app.ctx.pool, "student_exam", student_exam_id, {"status": 1})
    data = {"student_no": params.get("student_no"), "exam_paper_id": exam_paper_id, "objective_score": score,
            "score": score, "student_exam_id": student_exam_id}
    await create_item(app.ctx.pool, "student_score", data)